package com.spit.fammo.ui.frg

import android.os.Bundle
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.StringUtils
import com.spit.amoeba.base.BaseFragment
import com.spit.amoeba.weight.recyclerview.SpaceItemDecoration
import com.spit.fammo.adapter.StockTakeAsetAdapter
import com.spit.fammo.api.UIHelper
import com.spit.fammo.databinding.BNotTitleRecyclerBinding
import com.spit.fammo.ext.ASSET_FAIL_PAGE
import com.spit.fammo.ext.ASSET_STOCK_PAGE
import com.spit.fammo.ext.init
import com.spit.fammo.ext.setNbOnItemClickListener
import com.spit.fammo.viewmodel.AssetModel
import com.spit.fammo.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.nav
import java.util.concurrent.locks.ReentrantLock

/**
 * @Author nike
 * @Date 2023/7/27 16:18
 * @Description 全部
 */
class StockTakeAllFrg: BaseFragment<AssetModel, BNotTitleRecyclerBinding>(){

    val assetModel: AssetModel by activityViewModels()

    val rfidModel: RfidModel by activityViewModels()

    val adapter: StockTakeAsetAdapter by lazy { StockTakeAsetAdapter(arrayListOf()) }

    val lock = ReentrantLock()

    override fun initView(savedInstanceState: Bundle?) {
        arguments?.let {
            mViewModel.orderId.set(it.getString("orderId"))
            mViewModel.name.set(it.getString("name"))
        }
        mDatabind.swipeRefresh.isEnabled = false
        //初始化recyclerView
        mDatabind.recyclerView.itemAnimator = null
        mDatabind.recyclerView.init(LinearLayoutManager(context), adapter).let {
            it.addItemDecoration(SpaceItemDecoration(ConvertUtils.dp2px(20f), ConvertUtils.dp2px(20f), true))
        }
        adapter.run {
            setNbOnItemClickListener{adapter, view, position ->
                val bean = mFilterList[position]
                UIHelper.startAssetsDetailFrg(nav(), bean, bean.assetno, 0)
            }
        }

        mViewModel.onRequest(-1)

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)
                setToolBarTitle(mViewModel.name.get() + "(" + adapter.mFilterList.size + ")")
            }
        })
    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.listAssetBean.observe(viewLifecycleOwner, Observer {
            adapter.setList(it)
            adapter!!.appendList(it)
            setToolBarTitle(mViewModel.name.get() + "(" + adapter.mFilterList.size + ")")
        })
        //搜索
        assetModel.searchTextData.observe(viewLifecycleOwner, {
            mViewModel.searchText.set(it)
            adapter!!.filter.filter(it)
            if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                GlobalScope.launch(Dispatchers.Main) {
                    delay(300)
                    setToolBarTitle(mViewModel.name.get() + "(" + adapter.mFilterList.size + ")")
                }
            }
        })

        assetModel.epcListAssetUploadData.observe(viewLifecycleOwner, {
            if (it.isNullOrEmpty()) return@observe
            val filteredList = it.filter { it.type != ASSET_FAIL_PAGE }
            if (filteredList.size == 0)return@observe
            adapter.uploadList(filteredList)
            if (!StringUtils.isEmpty(mViewModel.searchText.get())){
                adapter!!.filter.filter(mViewModel.searchText.get())
            }
            if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                GlobalScope.launch(Dispatchers.Main) {
                    delay(300)
                    setToolBarTitle(mViewModel.name.get() + "(" + adapter.mFilterList.size + ")", true)
                }
            }
        })

        //识别RFID
        assetModel.epcAssetUploadData.observe(viewLifecycleOwner, {bean ->
            if (bean == null || bean.type == ASSET_FAIL_PAGE)return@observe
            var index = adapter.data.indexOfFirst { bean.epc == it.epc && bean.assetno == it.assetno}
            if (index != -1){
//                val assetBean = adapter.data[index]
                adapter.setData(index, bean)

                if (!StringUtils.isEmpty(mViewModel.searchText.get())){
                    adapter!!.filter.filter(mViewModel.searchText.get())
                }
                if (viewLifecycleOwner.lifecycle.currentState == Lifecycle.State.RESUMED) {
                    GlobalScope.launch(Dispatchers.Main) {
                        delay(300)
                        setToolBarTitle(mViewModel.name.get() + "(" + adapter.mFilterList.size + ")")
                    }
                }
            }
        })
    }

}